// 获取DOM元素
const searchInput = document.getElementById('searchInput');
const searchButton = document.getElementById('searchButton');
const prevPageButton = document.getElementById('prevPageButton');
const nextPageButton = document.getElementById('nextPageButton');
const orderTableBody = document.getElementById('orderTableBody');
const pageInfo = document.querySelector('.page-active');

// 分页相关变量
let currentPage = 1;
const perPage = 5; // 每页显示5条订单
let totalOrders = 0;
let debounceTimer; // 防抖计时器

// 加载订单数据
async function loadOrders(keyword = '', page = 1) {
    try {
        // 模拟API请求 - 实际项目中替换为真实API调用
        // const response = await fetch(`/api/orders?keyword=${keyword}&page=${page}&per_page=${perPage}`);
        // const data = await response.json();

        // 模拟数据 - 实际项目中删除这部分
        const mockData = {
            orders: [
                {
                    order_id: 'SCFY20250001',
                    product_name: '青花瓷瓶',
                    product_image: '../img/轮播图图片01.jpeg',
                    quantity: 1,
                    price: 1280.00,
                    order_time: '2025年1月17日 08:00',
                    status: 'pending'
                },
                {
                    order_id: 'SCFY20250002',
                    product_name: '古风折扇',
                    product_image: '../img/轮播图图片04.jpg',
                    quantity: 2,
                    price: 360.00,
                    order_time: '2025年2月10日 18:21',
                    status: 'shipped'
                },
                {
                    order_id: 'SCFY20250003',
                    product_name: '蜀绣手帕',
                    product_image: '../img/轮播图图片02.jpg',
                    quantity: 3,
                    price: 198.00,
                    order_time: '2025年3月5日 10:15',
                    status: 'delivered'
                },
                {
                    order_id: 'SCFY20250004',
                    product_name: '漆器茶具',
                    product_image: '../img/轮播图图片03.jpg',
                    quantity: 1,
                    price: 899.00,
                    order_time: '2025年3月18日 14:30',
                    status: 'pending'
                },
                {
                    order_id: 'SCFY20250005',
                    product_name: '竹编花篮',
                    product_image: '../img/轮播图图片05.jpg',
                    quantity: 2,
                    price: 256.00,
                    order_time: '2025年4月1日 09:45',
                    status: 'shipped'
                }
            ],
            total: 15
        };

        // 模拟搜索过滤
        let filteredOrders = mockData.orders;
        if (keyword) {
            filteredOrders = mockData.orders.filter(order =>
                order.order_id.includes(keyword) ||
                order.product_name.includes(keyword)
            );
        }

        // 模拟分页
        const startIndex = (page - 1) * perPage;
        const paginatedOrders = filteredOrders.slice(startIndex, startIndex + perPage);
        totalOrders = filteredOrders.length;

        // 渲染订单表格
        renderOrders(paginatedOrders);

        // 更新分页信息
        updatePaginationInfo(page, Math.ceil(totalOrders / perPage));

    } catch (error) {
        console.error('加载订单出错:', error);
        orderTableBody.innerHTML = `<tr><td colspan="5" class="text-center">加载订单失败，请稍后重试</td></tr>`;
    }
}

// 渲染订单列表
function renderOrders(orders) {
    if (orders.length === 0) {
        orderTableBody.innerHTML = `<tr><td colspan="5" class="text-center">未找到相关订单</td></tr>`;
        return;
    }

    orderTableBody.innerHTML = orders.map(order => `
        <tr>
            <td>${order.order_id}</td>
            <td>
                <div class="product-info">
                    <img src="${order.product_image}" alt="${order.product_name}">
                    <div>
                        <div class="product-name">${order.product_name}</div>
                        <div class="product-spec">数量: ${order.quantity} | ￥${order.price.toFixed(2)}</div>
                    </div>
                </div>
            </td>
            <td>${order.order_time}</td>
            <td>
                <span class="status status-${order.status}">
                    ${getStatusText(order.status)}
                </span>
            </td>
            <td>
                <button class="btn btn-detail"><a href="商品信息.html">详情</a></button>
                ${order.status === 'pending' ?
        '<button class="btn btn-cancel">取消</button>' :
        order.status === 'shipped' ?
            '<button class="btn btn-track"><a href="用户物流管理.html">物流跟踪</a></button>' :
            ''}
            </td>
        </tr>
    `).join('');
}

// 获取订单状态文本
function getStatusText(status) {
    const statusMap = {
        'pending': '待发货',
        'shipped': '已发货',
        'delivered': '已送达',
        'cancelled': '已取消'
    };
    return statusMap[status] || status;
}

// 更新分页信息
function updatePaginationInfo(currentPage, totalPages) {
    pageInfo.textContent = currentPage;

    // 禁用/启用上一页按钮
    prevPageButton.disabled = currentPage === 1;

    // 禁用/启用下一页按钮
    nextPageButton.disabled = currentPage === totalPages || totalPages === 0;
}

// 搜索按钮点击事件
searchButton.addEventListener('click', () => {
    const keyword = searchInput.value.trim();
    currentPage = 1;
    loadOrders(keyword, currentPage);
});

// 输入框输入事件，添加防抖功能
searchInput.addEventListener('input', () => {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
        const keyword = searchInput.value.trim();
        currentPage = 1;
        loadOrders(keyword, currentPage);
    }, 500);
});

// 上一页按钮点击事件
prevPageButton.addEventListener('click', () => {
    if (currentPage > 1) {
        currentPage--;
        const keyword = searchInput.value.trim();
        loadOrders(keyword, currentPage);
    }
});

// 下一页按钮点击事件
nextPageButton.addEventListener('click', () => {
    const keyword = searchInput.value.trim();
    const totalPages = Math.ceil(totalOrders / perPage);

    if (currentPage < totalPages) {
        currentPage++;
        loadOrders(keyword, currentPage);
    }
});

// 初始化加载第一页数据
loadOrders();